<template>
  <div>
    <el-form
      v-loading="loading"
      class="message-content"
      ref="form"
      :model="form"
      label-width="80px"
      label-position="top"
      hide-required-asterisk
    >
      <div class="send-obj">
        
        <el-form-item
          v-if="form.sendTargetParam && module !== 'universal'"
          label="通知对象" 
          prop="sendTargetParam"
          :rules="{ required:true, validator: checkSendTarget,trigger: ['change'] }"
        >
          
          <publink-select
            v-if="type === 'inside'"
            class="user-target-select"
            ref="userComponentSelect"
            placeholder="请选择"
            collapse-tags
            @clear="clearSelectUserHandle"
            @click.native="onTriggerSelectUserHandler"
            @remove-tag="removeTagHandle"
            v-model="form.sendTargetParam.all"
            is-search-user
            value-key="id"
            multiple
          >
            <el-option
              v-for="item in form.sendTargetParam.all"
              :key="item.id"
              :label="item.name"
              :origin="item"
              :value="item">
              
              <template v-if="isOpenData && item.staffId && item.typeId == 1">
                <open-data type="userName" :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                {{ item.name }}
              </template>
              
            </el-option>

          </publink-select>

          <el-select
            v-else
            placeholder="请选择"
            collapse-tags
            @change="selectCustomerChangeHandler"
            v-model="form.sendTargetParam.nameStr"
            multiple
          >
            <el-option v-for="item in dynamicFieldList" :label="item.name" :value="item.id" :key="item.id" />
          </el-select>

        </el-form-item>
        
      </div>

      <el-form-item v-if="showTimeField" label="发送时间" prop="taskPlanTime">
        在计划时间到期前
        <el-input
          style="width:68px;margin:0 10px 0 14px;"
          type="text"
          v-model="form.taskPlanTime"
          @input="timeInputHandle">
        </el-input>
        小时(允许设置为小数)发送短信提醒客户，为空时不提醒
      </el-form-item>

      <el-form-item  label="通知方式" prop="taskPlanTime">
        <el-radio-group v-model="form.notifyConfig.mode">
          <el-radio label="once">通知一次</el-radio>
          <el-radio label="circular">循环通知</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item  label="通知时间" prop="taskPlanTime" v-if="form.notifyConfig.mode === 'once'">
        <el-radio-group v-model="form.notifyConfig.timeType">
          <el-radio label="now">即刻</el-radio>
          <el-radio label="dynamic">动态时间</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item  label="通知开始时间" prop="taskPlanTime" v-if="form.notifyConfig.mode === 'circular'">
        <el-radio-group v-model="form.notifyConfig.timeType">
          <el-radio label="fixed">触发时间</el-radio>
          <el-radio label="dynamic">动态时间</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 通知开始时间 -->
      <el-form-item class="group-el-form-item" v-if="form.notifyConfig.mode === 'circular' && form.notifyConfig.timeType === 'dynamic'" prop="startConfig" :rules="{ required: true, validator: notifyConfigStartConfigValidate, trigger: ['change'] }">
        <el-form-item>
          <el-select v-model="form.notifyConfig.startConfig.fieldName" placeholder="请选择" @change="notifyConfigValidate('startConfig', notifyConfigStartConfigValidate)">
            <el-option v-for="i in motifyConfigFields" :key="i.enName" :label="i.cnName" :value="i.enName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="form.notifyConfig.startConfig.dateStatus" placeholder="请选择" @change="notifyConfigValidate('startConfig', notifyConfigStartConfigValidate)">
            <el-option label="之前" value="before"></el-option>
            <el-option label="之后" value="after"></el-option>
            <el-option label="当天" value="on"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.notifyConfig.startConfig.dateStatus !== 'on'">
          <el-input-number :controls="false" v-model="form.notifyConfig.startConfig.number" :min="0" @change="notifyConfigValidate('startConfig', notifyConfigStartConfigValidate)"></el-input-number>
        </el-form-item>
        <el-form-item v-if="form.notifyConfig.startConfig.dateStatus !== 'on'">
          <el-select v-model="form.notifyConfig.startConfig.dataType" placeholder="请选择" @change="notifyConfigValidate('startConfig', notifyConfigStartConfigValidate)">
            <el-option label="天" value="days"></el-option>
            <el-option label="周" value="weeks"></el-option>
            <el-option label="月" value="months"></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>

      <!-- 通知方式 -->
      <el-form-item class="group-el-form-item" label="通知方式" v-if="form.notifyConfig.mode === 'circular'" prop="strategyType" :rules="{ required: true, validator: notifyConfigStrategyTypeValidate, trigger: ['change'] }">
        <el-form-item style="margin-right: 12px;">
          <el-select v-model="form.notifyConfig.strategyConfig.strategyType" placeholder="请选择" @change="notifyConfigValidate('strategyType', notifyConfigStrategyTypeValidate)">
            <el-option label="每天" value="everyDay"></el-option>
            <el-option label="每周" value="everyWeek"></el-option>
            <el-option label="每月" value="everyMonth"></el-option>
            <el-option label="自定义天数" value="fixedDays"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-right: 12px;" v-if="form.notifyConfig.strategyConfig.strategyType === 'everyWeek'">
          <el-select v-model="form.notifyConfig.strategyConfig.nums" placeholder="请选择" multiple  @change="notifyConfigValidate('strategyType', notifyConfigStrategyTypeValidate)">
            <el-option v-for="i in weekOptions()" :key="i.value" :label="i.label" :value="i.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-right: 12px;" v-if="form.notifyConfig.strategyConfig.strategyType === 'everyMonth'">
          <el-select v-model="form.notifyConfig.strategyConfig.nums" placeholder="请选择" multiple  @change="notifyConfigValidate('strategyType', notifyConfigStrategyTypeValidate)">
            <el-option v-for="i in dayOptions()" :key="i.value" :label="i.label" :value="i.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-right: 12px;" v-if="form.notifyConfig.strategyConfig.strategyType === 'fixedDays'">
          <span style="margin-right: 12px;">每</span>
          <el-input-number :controls="false" v-model="form.notifyConfig.strategyConfig.nums"  :min="1" :max="9999" @change="notifyConfigValidate('strategyType', notifyConfigStrategyTypeValidate)"></el-input-number>
          <span style="margin-left: 12px;">天</span>
        </el-form-item>
        

        <el-form-item style="margin-right: 12px;">
          <el-select v-model="form.notifyConfig.strategyConfig.onTheHour" placeholder="请选择" style="width: 85px;"  @change="notifyConfigValidate('strategyType', notifyConfigStrategyTypeValidate)">
            <el-option v-for="i in hourOptions()" :key="i.value" :label="i.label" :value="i.value"></el-option>
          </el-select>
        </el-form-item>
        <span>时</span>
      </el-form-item>

      <!-- 通知结束时间 | 动态时间 -->
      <el-form-item :label="form.notifyConfig.mode === 'circular' ? '通知结束时间' : ''" v-if="['dynamic', 'fixed'].includes(form.notifyConfig.timeType)" prop="endConfig" :rules="{ required: true, validator: notifyConfigEndConfigValidate, trigger: ['change'] }">
        <el-form-item v-if="form.notifyConfig.mode === 'circular'">
          <el-radio-group v-model="form.notifyConfig.endConfig.mode">
            <el-radio label="dynamic">按动态时间结束</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="group-el-form-item group-el-form-item-no-margin">
          <el-form-item>
            <el-select v-model="form.notifyConfig.endConfig.fieldName" placeholder="请选择" @change="notifyConfigValidate('endConfig', notifyConfigEndConfigValidate)">
              <el-option v-for="i in motifyConfigFields" :key="i.enName" :label="i.cnName" :value="i.enName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="form.notifyConfig.endConfig.dateStatus" placeholder="请选择" @change="notifyConfigValidate('endConfig', notifyConfigEndConfigValidate)">
              <el-option label="之前" value="before"></el-option>
              <el-option label="之后" value="after"></el-option>
              <el-option label="当天" value="on"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.notifyConfig.endConfig.dateStatus !== 'on'">
            <el-input-number :controls="false" v-model="form.notifyConfig.endConfig.number" :min="0" :max="9999" @change="notifyConfigValidate('endConfig', notifyConfigEndConfigValidate)"></el-input-number>
          </el-form-item>
          <el-form-item v-if="form.notifyConfig.endConfig.dateStatus !== 'on'">
            <el-select v-model="form.notifyConfig.endConfig.dataType" placeholder="请选择" @change="notifyConfigValidate('endConfig', notifyConfigEndConfigValidate)">
              <el-option label="天" value="days"></el-option>
              <el-option label="周" value="weeks"></el-option>
              <el-option label="月" value="months"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.notifyConfig.mode === 'once'">
            <el-select v-model="form.notifyConfig.endConfig.onTheHour" placeholder="请选择" style="width: 85px;" @change="notifyConfigValidate('endConfig', notifyConfigEndConfigValidate)">
              <el-option v-for="i in hourOptions()" :key="i.value" :label="i.label" :value="i.value"></el-option>
            </el-select>
          </el-form-item>
          <span v-if="form.notifyConfig.mode === 'once'">时</span>
        </el-form-item>
      </el-form-item>
            
      <el-form-item 
        label="通知渠道"
        prop="sendChannelList"
        class="send-channel-list"
        :rules="{ required: true, type:'array' ,message: '请选择通知渠道'}"
      >
        <el-checkbox-group v-model="form.sendChannelList">

          <div class="channel-item" v-for="(item) in channelList" :key="item.channelType">
            <!-- 通用消息- 系统消息默认不可以去除选中 -->
            <el-checkbox
              @change="(val) => { sendChannelChangeHandle(item.channelType,val)}"
              :label="item.channel"
              :disabled="module === 'universal' && item.channel == 1"
            >
              {{item.channelTypeDescription}}
            </el-checkbox>

          </div>

        </el-checkbox-group>
      </el-form-item>

      <el-tabs class="channel-tab" v-model="activeName" >
  
        <template v-for="tab in channelList">
          <el-tab-pane
            :class="['template-content', tab.channelType === 'call' ? 'template-content__call' : null]"
            :label="tab.channelTypeDescription"
            :name="tab.channelType"
            :key="tab.channelType"
            v-if="dialogVisible"
          >
            <!-- 系统消息模版 -->
            <SystemMesTel 
              v-if="tab.channelType === 'sysMsg'" 
              ref="sysMsg"
              :channel="tab.channel"
              :type="type"
              :send-channel-list="form.sendChannelList"
              :source-data="systemTemplate"
              :is-validate-change="false"
              :is-trigger="true"
            />

            <!-- 短信消息模版 -->
            <SmsMesTel 
              v-else-if="tab.channelType === 'smsMsg'" 
              ref="smsMsg"
              :channel="tab.channel"
              :type="type"
              :readonly="module === 'universal'"
              :send-channel-list="form.sendChannelList"
              :source-data="smsTemplate"
              :modules="triggerTemplateField"
              :is-validate-change="false"
              @update="update"
            />

            <!-- 电话消息模版 -->
            <CallMesTel 
              v-else-if="tab.channelType === 'call'" 
              ref="call"
              :channel="tab.channel"
              :type="type"
              :send-channel-list="form.sendChannelList"
              :source-data="callTemplate"
              :is-validate-change="false"
            />

            <!-- 没绑定邮箱或公众号时展示 -->
            <no-auth
              v-else-if="isShowNoAuth(tab.channelType)"
              :is-button-show="true"
              :tips-pic="noAuthPic"
              :button-text="bindData[tab.channelType].btnText"
              :tips-text="bindData[tab.channelType].tips"
              @btn-event="btnEvent(tab.channelType)"
            />
            
            <!-- 邮件消息模版 -->
            <EmailMessage  
              v-else-if="tab.channelType === 'emailMsg'"
              ref="emailMsg"
              :channel="tab.channel"
              :type="type"
              :readonly="module === 'universal' || messageTypeName === 'satisfactionReturnVisitV2'"
              :send-channel-list="form.sendChannelList"
              :source-data="emailTemplate"
              :modules="triggerTemplateField"
              :is-validate-change="false"
              :is-trigger="true"
            />

            <!-- 公众号消息模版 -->
            <WechatMesTel 
              v-else-if="tab.channelType === 'weixin'" 
              ref="weixin"
              :channel="tab.channel"
              :type="type"
              :send-channel-list="form.sendChannelList"
              :source-data="wechatTemplate"
              :is-validate-change="false"
            />
            
          </el-tab-pane>
        </template>
      </el-tabs>
    </el-form>

  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import { BaseSelectUserTreeComponent, BaseSelectUserNoDataView } from '@src/component/common/BaseSelectUser/components'
// 系统消息模版
import SystemMesTel from '../messageTel/SystemMesTel.vue'
// 短信消息模版
import SmsMesTel from '../messageTel/SmsMesTel.vue'
// 公众号消息模版
import WechatMesTel from '../messageTel/WechatMesTel.vue'
// 电话消息模版
import CallMesTel from '../messageTel/CallMesTel.vue'
// 邮件消息模版
import EmailMessage from '../emailMessage/EmailMessage'

// 未绑定提示组件
import noAuth from '@src/component/auth/noAuth'
// 接口
import * as Message from '@src/api/Message';
import * as FlowApi from '@src/api/FlowApi.ts';
import { getOssUrl } from '@src/util/assets'
const noAuthPic = getOssUrl('/no_data.png')
import { sendObject } from '../../modal/messageData'


import { openAccurateTab } from '@src/util/platform';

import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum'

/* hooks */
import MsgModel from '@model/MsgModel'
/* util */
import { cloneDeep, isNumber } from 'lodash'
/* mixin */
import { VersionControlMessageMixin } from '@src/mixins/versionControlMixin'

const SHOW_TAB_SETTING = { show: true, isMulti: true };

const init_notifyConfig = {
  init: true,
  mode: 'once', // "once-通知一次，circular-循环通知",
  timeType: 'now', // "now-即刻通知，dynamic-动态【时间】，fixed-【触发时间】",
  startConfig: {
    mode: 'dynamic', // "dynamic-动态的，需要配置字段的", 目前也只有这种
    fieldName: '', // "field_xxxx",//表单字段fieldName
    dateStatus: '', //  "before-之前,after-之后,on-当天",
    number: undefined, // 之前几天，之后几天，标明几的
    dataType: '', // "days-天，weeks-周，months-月",
    onTheHour: undefined, // 在几点触发
  },
  endConfig: {
    mode: 'dynamic', // "dynamic-动态的，需要配置字段的", 目前也只有这种
    fieldName: '', // "field_xxxx",//表单字段fieldName
    dateStatus: '', //  "before-之前,after-之后,on-当天",
    number: undefined, // 之前几天，之后几天，标明几的
    dataType: '', // "days-天，weeks-周，months-月",
    onTheHour: undefined, // 在几点触发
  },
  strategyConfig: {
    strategyType: '', // "everyDay-每天,everyWeek-每周,everyMonth-每月,fixedDays-自定义天数",
    onTheHour: undefined, // 在几整点
    nums: undefined, // 每周的周几 或 者每月的几号 或 每n天 使用这个参数.比如 每周的周一和周五，这里就是[1,5],比如 每月的1号，23号，28号，这里就是[1,23,28],比如 每20天，这里就是[20]
  }
}

export default {
  name: 'set-message-content',
  mixins: [VersionControlMessageMixin],
  props:{
    // 消息节点的配置数据
    nodeConfig: {
      type: Object,
      default: () => ({}),
    },
    // 消息类型 inside：内部，customer：客户
    type: {
      type:String,
      required:true
    },

    // 消息类型名称英文 触发器节点Id
    messageTypeName: {
      type:[String, Number],
    },

    // 弹框显示/隐藏
    value: {
      type:Boolean,
      required:true
    },

    reportSendTime:{
      type:String,
      required:false
    },
    bizType: {
      type: String,
      required: false,
      default: '',
    },
    bizTypeId: {
      type: String,
      required: false,
      default: '',
    },
    bizTypeIds: {
      type: Array,
      required: false,
      default: ()=> [],
    }
  },
  data(){
    return{
      loading: false,
      isOpenData,
      // 通知渠道；
      // 内部消息有系统消息、短信消息和邮件消息三个渠道
      // 客户消息短信消息、公众号消息和邮件消息三个渠道
      channelList: [],
      form: {
        sendChannelList: [],
        // 通知对象
        sendTargetParam: {
          all: [],
          nameStr: [],
          tagList: [], // 选人组件选择的部门
          userList: [], // 选人组件选择的用户
          roleList: [], // 选人组件选择的角色
          userTypeList: [], // select组件选择的大类别通知对象
          paasReceiver: ''
        },
        // 定时设置
        notifyConfig: cloneDeep(init_notifyConfig),
      },
      motifyConfigFields: [],

      // 传递给模版的数据，从接口获取
      // 系统消息模版需要的数据
      systemTemplate:{},
      // 短信消息模版需要的数据
      smsTemplate:{},
      // 邮件消息模版需要的数据
      emailTemplate:{},
      // 公众号消息模版需要的数据
      wechatTemplate:{},
      // 电话消息模版需要的数据
      callTemplate:{},

      // 微信公众号/邮箱绑定数据
      bindData:{
        weixin:{
          isSetUp:true,
          btnText:'绑定公众号',
          tips:'您尚未绑定公众号，绑定前请确认您的公众号为已认证的公众号'
        },
        emailMsg:{
          isSetUp:true,
          btnText:'去配置',
          tips:'暂未配置邮箱'
        },
      },

      // 没权限时提示图片
      noAuthPic,

      // 选中的tab的name
      activeName:'',

      sendList:[],

      // 应用范围列表数据
      applicationRange:[],

      sendObject,
      showPaasContactTabSetting: {
        department: { ...SHOW_TAB_SETTING },
        member: { ...SHOW_TAB_SETTING },
        role: { ...SHOW_TAB_SETTING},
        dynamic: { ...SHOW_TAB_SETTING }
      },
      isDynamicFlowDesignChoose: true,  // 判断是动态获取的话设置支持节点负责人获取节点的列表
      showDynamicMenus: [],
      triggerTemplateField: [],
      dynamicFieldList: [], // 表单动态获取字段
      side: 0, // 判断是内部还是外部通知 0内部 1外部
      messageConfig: null, // 消息配置
      tenantConfig: null, //
      sendTargetMap: {
        'inside': {
          nameStr: '',
          selectedDynamicList: [],
          selectedDepartments: [],
          selectedUsers: [],
          selectedRoles: [],
          selectedServiceProviders: [],
          userTypeList:[]
        },
        'customer': {
          nameStr: '',
          selectedDynamicList: [],
        },
      }, // 保存通知对象
    }
  },
  inject: ['module', 'flowData', 'projectData'],
  computed:{
    // 消息id
    configId() {
      return this.tenantConfig?.configId
    },
    dialogVisible:{
      get(){
        return this.value;
      },
      set(val){
        this.$emit('input', val)
      }
    },
    // 展示时间表单字段
    showTimeField(){
      return this.type === 'customer' && this.messageTypeName === 'TaskPlanRemind_NEW'
    },
    // 返回true，表示该部分为选人组件
    isSelectUserComponent(){
      // 都使用选人组件
      return true
      // const sendList = this.sendList
      // return (sendList.length === 1 && sendList.includes(5)) || this.module === 'paas'
    },
    flowApi() {
      return { ...FlowApi };
    }
  },
  components:{
    BaseSelectUserTreeComponent,
    BaseSelectUserNoDataView,
    SystemMesTel,
    SmsMesTel,
    WechatMesTel,
    CallMesTel,
    noAuth,
    EmailMessage,
  },
  watch: {
    type: {
      handler(newVal, oldVal) {
        this.side = newVal === 'inside' ? 0 : 1
        this.getDynamicMessageField()     
        console.log(this.messageConfig, this.tenantConfig)
        // 切换内部和外部通知
        this.getChannelTemplateDetail(this.messageConfig)
        // 清空发送对象需要延时一下
        setTimeout(() => {
          this.$nextTick(()=>{
            const sendTargets = this.sendTargetMap[newVal]
            this.$set(this.form,'sendTargetParam', sendTargets)
          })
        }, 100);
      }
    },
    'form.notifyConfig.mode': {
      handler(val) {
        if(init_notifyConfig.init){
          this.$nextTick(() => {
            init_notifyConfig.init = false
          })
          return
        }
        if(val === 'circular'){
          this.form.notifyConfig.timeType = 'fixed'
        }else if(val === 'once'){
          this.form.notifyConfig.timeType = 'now'
        }
      }
    },
    'form.notifyConfig.timeType': {
      handler() {
        // 第一次变动时，不要重置
        if(init_notifyConfig.init){
          return
        }
        this.form.notifyConfig.startConfig = {...init_notifyConfig.startConfig}
        this.form.notifyConfig.endConfig = {...init_notifyConfig.endConfig}
        this.form.notifyConfig.strategyConfig = {...init_notifyConfig.strategyConfig}
      }
    },
    'form.notifyConfig.strategyConfig.strategyType': {
      handler() {
        // 第一次变动时，不要重置
        if(init_notifyConfig.init){
          return
        }
        this.form.notifyConfig.strategyConfig.nums = undefined
      }
    },
    'form.notifyConfig.endConfig.dateStatus': {
      handler(val){
        // 第一次变动时，不要重置
        if(init_notifyConfig.init){
          return
        }
        if(val === 'on'){
          this.form.notifyConfig.endConfig.number = undefined
          this.form.notifyConfig.endConfig.dataType = ''
        }
      }
    },
    'form.notifyConfig.startConfig.dateStatus': {
      handler(val){
        // 第一次变动时，不要重置
        if(init_notifyConfig.init){
          return
        }
        if(val === 'on'){
          this.form.notifyConfig.startConfig.number = undefined
          this.form.notifyConfig.startConfig.dataType = ''
        }
      }
    },
  },
  mounted(){
    // 触发器选人都存在paasReceiver参数中，sendTargetPartList不需要传
    this.openHandle()
  },
  methods:{
    // 时间枚举值
    hourOptions(){
      return Array.from({length:24}, (_, i)=> ({label: +i, value: +i }) )
    },
    // 周枚举值
    weekOptions() {
      return [
        { label: '周一', value: 1},
        { label: '周二', value: 2},
        { label: '周三', value: 3},
        { label: '周四', value: 4},
        { label: '周五', value: 5},
        { label: '周六', value: 6},
        { label: '周日', value: 7},
      ]
    },
    // 天枚举值
    dayOptions(){
      return Array.from({length:31}, (_, i)=> ({label: `${+i + 1}日`, value: +i + 1 }) )
    },

    update() {
      // 短信提交审核后更新信息 触发器不能通过接口获取详情 
      const channelItem = this.channelList.find(item=>item.channelType === 'smsMsg')
      const { channelType } = channelItem
      const channelDom = this.$refs[channelType] && this.$refs[channelType][0]
      const { smsTemplateParam = {} } = channelDom.getParam()
      const { usageSmsContent } = this.messageConfig.smsTemplate
      smsTemplateParam.usageSmsContent = usageSmsContent
      smsTemplateParam.approveSmsContent = smsTemplateParam.applyContent
      let param = {
        channelType: 'smsMsg',
        templateName: 'smsTemplate',
        templateData: smsTemplateParam
      }
      this.updateMsgTemplateData(param);
      this.$refs.smsMsg?.[0]?.editorHandle(false)
    },

    checkSendTarget(rule, value, callback) {
      const { userTypeList, nameStr, all } = value
      // 非选人组件的校验或选人组件
      if( this.isSelectUserComponent && nameStr.length && !all.length) {
        return callback(new Error('请选择通知对象'));
      }  
      if(!this.isSelectUserComponent && !userTypeList.length){
        return callback(new Error('请选择通知对象'));
      }

      return callback ? callback() : ''
    },

    // 通知开始时间校验
    notifyConfigStartConfigValidate(rule, value, callback){
      if(!this.form.notifyConfig.startConfig.fieldName || !this.form.notifyConfig.startConfig.dateStatus){
        return callback ? callback(new Error('请填写通知开始时间')) : new Error('请填写通知开始时间')
      }
      if(['before', 'after'].includes(this.form.notifyConfig.startConfig.dateStatus)){
        if(!this.form.notifyConfig.startConfig.number || !this.form.notifyConfig.startConfig.dataType){
          return callback ? callback(new Error('请填写通知开始时间')) : new Error('请填写通知开始时间')
        }
      }
      return callback ? callback() : ''
    },
    // 通知方式校验
    notifyConfigStrategyTypeValidate(rule, value, callback){
      if(!this.form.notifyConfig.strategyConfig.strategyType || (!this.form.notifyConfig.strategyConfig.onTheHour && this.form.notifyConfig.strategyConfig.onTheHour !== 0)){
        return callback ? callback(new Error('请填写通知方式')) : new Error('请填写通知方式')
      }
      if(['everyWeek', 'everyMonth', 'fixedDays'].includes(this.form.notifyConfig.strategyConfig.strategyType)){
        if(!this.form.notifyConfig.strategyConfig.nums){
          return callback ? callback(new Error('请填写通知方式')) : new Error('请填写通知方式')
        }
      }
      return callback ? callback() : ''
    },
    // 通知结束时间 | 动态时间 校验
    notifyConfigEndConfigValidate(rule, value, callback){
      if(this.form.notifyConfig.mode === 'once'){
        if(!this.form.notifyConfig.endConfig.fieldName || !this.form.notifyConfig.endConfig.dateStatus){
          return callback ? callback(new Error('请填写动态时间')) : new Error('请填写动态时间')
        }
        if(!this.form.notifyConfig.endConfig.onTheHour && this.form.notifyConfig.endConfig.onTheHour !== 0){
          return callback ? callback(new Error('请填写动态时间')) : new Error('请填写动态时间')
        }
        if(['before', 'after'].includes(this.form.notifyConfig.endConfig.dateStatus)){
          if( !isNumber(this.form.notifyConfig.endConfig.number) || !this.form.notifyConfig.endConfig.dataType){
            return callback ? callback(new Error('请填写动态时间')) : new Error('请填写动态时间')
          }
        }
      }else if(this.form.notifyConfig.mode === 'circular'){
        if(!this.form.notifyConfig.endConfig.fieldName || !this.form.notifyConfig.endConfig.dateStatus){
          return callback ? callback(new Error('请填写通知结束时间')) : new Error('请填写通知结束时间')
        }
        if(['before', 'after'].includes(this.form.notifyConfig.endConfig.dateStatus)){
          if( !this.form.notifyConfig.endConfig.number || !this.form.notifyConfig.endConfig.dataType){
            return callback ? callback(new Error('请填写通知结束时间')) : new Error('请填写通知结束时间')
          }
        }
      }
      return callback ? callback() : ''
    },
    notifyConfigValidate(field, validate){
      this.$refs.form.validateField(field, validate)
    },
  
    // 通过名字匹配，当delName === selectedArr数组某个元素的name或displayName时，从selectedArr数组里面去除该元素
    delSendTarget(selectedArr,delName){
      let newSelectedArr = []
      for(let target of selectedArr){
        const name = target.name || target.displayName

        if(name !== delName) {
          newSelectedArr.push(target)
        }
      }
      return newSelectedArr
    },

    clearSelectUserHandle(){
      const sendTargetParam = {
        all: [],
        nameStr: [],
        selectedDepartments:[],
        selectedUsers:[],
        selectedRoles:[],
        userTypeList:[],
        selectedServiceProviders:[],
        selectedDynamicList:[],
      }
      this.$set(this.form,'sendTargetParam', sendTargetParam)
      this.$set(this.sendTargetMap,'inside', sendTargetParam)
    },

    // 删除某个发送对象
    removeTagHandle(target){
      const delName = target.name || target.displayName
      const { all, selectedDepartments, selectedUsers, selectedRoles, selectedDynamicList, selectedServiceProviders } = this.form.sendTargetParam

      this.$set(this.form.sendTargetParam,'all',this.delSendTarget(all,delName))
      this.$set(this.form.sendTargetParam,'selectedDepartments',this.delSendTarget(selectedDepartments,delName))
      this.$set(this.form.sendTargetParam,'selectedUsers',this.delSendTarget(selectedUsers,delName))
      this.$set(this.form.sendTargetParam,'selectedRoles',this.delSendTarget(selectedRoles,delName))
      this.$set(this.form.sendTargetParam,'selectedDynamicList',this.delSendTarget(selectedDynamicList,delName))
      this.$set(this.form.sendTargetParam,'selectedServiceProviders',this.delSendTarget(selectedServiceProviders,delName))

    },
    onTriggerSelectUserHandler() {

      this.$refs.userComponentSelect?.blur()
      
      const { selectedDepartments, selectedUsers, selectedRoles, selectedDynamicList, selectedServiceProviders } = this.form.sendTargetParam
      const defaultCheckedKeys = (selectedDynamicList || []).map(item => {
        return item.id
      })
      // console.log('defaultCheckedKeys', defaultCheckedKeys)
      const options = {
        title:'选择通知对象',
        showServiceProvider: true, // 是否显示服务商
        selectedDepartments: selectedDepartments || [],
        selectedUsers: selectedUsers || [],
        selectedRoles: selectedRoles || [],
        selectedDynamicList: selectedDynamicList || [],
        selectedServiceProviders: selectedServiceProviders || [],
        mode: 'filter',
        isTrigger: true,
        // 自定义渲染动态获取内容
        renderDynamicContent: (h, context) => {
          return (
            <div class="base-select-user-role-left trigger-base-select-user-dynamic-user-list">
        
              {/* start 动态获取字段列表页面 */}
              <BaseSelectUserTreeComponent
                v-show={this.dynamicFieldList.length}
                default-checked-keys={defaultCheckedKeys}
                data={this.dynamicFieldList}
                is-multi={true}
                show-checkbox={true}
              >
              </BaseSelectUserTreeComponent>
              {/* end 动态获取字段列表 */}
              
              {/* start 无数据显示 */}
              <BaseSelectUserNoDataView v-show={!this.dynamicFieldList.length} />
              {/* end 无数据显示 */}
              
            </div>
          )
        }
      }
      
      this.$fast.select.multi.all(options).then(result => {
        this.selectUserCallBack(result)
        
      })
      
      this.getDynamicMessageField()
    },

    // 选择外部人员变化
    selectCustomerChangeHandler(ids) {
      if(!ids.length) {
        this.$set(this.form,'sendTargetParam',{
          nameStr: '',
          selectedDynamicList: [],
        })
        this.$set(this.sendTargetMap,'customer',{
          nameStr: '',
          selectedDynamicList: [],
        })
        return
      }
      let nameArr = [], dynamicList = []
      this.dynamicFieldList.forEach(item=> {
        ids.forEach(id=> {
          if(item.id === id) {
            dynamicList.push(item)
            nameArr.push(item.id)
          }
        })
      })   
      this.$set(this.form,'sendTargetParam',{
        nameStr: nameArr,
        selectedDynamicList: dynamicList,
      })
      this.$set(this.sendTargetMap,'customer',{
        nameStr: nameArr,
        selectedDynamicList: dynamicList,
      })
    },
    // 发送消息选人点击动态获取表单上的动态字段
    async getDynamicMessageField() {
      try {
        const params = {
          apiIdList: this.bizTypeIds,
          side: this.type === 'inside' ? 0 : 1
        }
        const { data } = await Message.getDynamicMessageField(params)
        this.dynamicFieldList = (data || []).map(item=> {
          item.id = item.enName
          item.name = item.cnName
          item.typeId = 6 // 动态获取
          return item
        })
      } catch (e){
        console.warn(e)
      }
    },

    selectUserCallBack({status,data}){
      if(status !== 0) return
      let { users, roles, depts, serviceProviders = [], all = [] } = data;
      let nameArr = []
      const dynamicList = all.filter(item => item.typeId === 6)
      const selectedData = [ ...users, ...roles, ...depts, ...dynamicList, ...serviceProviders ]
      selectedData.map(item => {
        const { name, displayName} = item
        nameArr.push(name || displayName)
      })
      all = all.map(item =>{
        if(item.typeId == 1) {
          // 选人
          item.id = item.userId
          item.name = item.displayName
        }
        return item
      })
      const sendTargetParam = {
        all,
        nameStr: nameArr,
        selectedDynamicList: dynamicList,
        selectedDepartments:depts,
        selectedUsers:users,
        selectedRoles:roles,
        selectedServiceProviders: serviceProviders,
        userTypeList:[] 
      }
      this.$set(this.form,'sendTargetParam',sendTargetParam)
      this.$set(this.sendTargetMap,'inside', sendTargetParam)
    },

    // 时间输入框，限制输入,
    // 只能输入数字和小数点;只能输入一位小数点;
    timeInputHandle(){
      const { taskPlanTime } = this.form

      this.form.taskPlanTime = taskPlanTime.replace(/[^\d.]/g, '')
        .replace(/\.{2,}/g, '.')
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
        .replace(/^\./g, '')
    },

    // 是否展示当前渠道的模版,邮件消息和公众号消息需要判断是否配置了，没有配置不展示该模版
    isShowNoAuth(channelType){
      if(channelType !== 'emailMsg' && channelType !== 'weixin') return false;
      
      const { isSetUp } = this.bindData[channelType]
      return !isSetUp
    },

    sendChannelChangeHandle(channelType, val){
      // 智能报告类型的消息，需要对'smsMsg','emailMsg'进行联动
      if(this.module !== 'daily') return;

      const channelValidList = ['smsMsg', 'emailMsg']

      const { sendChannelList } = this.form

      // 当前操作的字段在channelValidList里，且是选中状态且通知渠道里面美誉勾选系统消息时，将系统消息这个渠道勾选上
      if(channelValidList.includes(channelType) && val && !sendChannelList.includes('sysMsg')){
        console.log('9898988')
        this.form.sendChannelList.push('1')
      }
    },
    
    // 弹框打开时触发
    async openHandle() {
      // console.log(3123123, this.bizTypeId)
      init_notifyConfig.init = true
      Message.getTemplateField(this.bizTypeIds).then(res => {
        this.motifyConfigFields = res.data || []
      })
      // 触发器获取表单字段用于消息替换
      await this.getTriggerTemplateField()
      // 获取触发器规则数据
      this.getTriggerRuleData()
    },
    initDefaultData() {
      const data = cloneDeep(this.nodeConfig.data || this.nodeConfig.fieldOptions)
      let { side, systemTemplateParam, smsTemplateParam, emailMsgTemplateParam, 
        wechatMessageTemplateParam, tenantConfig, channelList, sendChannelList, 
        sendTargetParam, notifyConfig, callingTemplateParam } = data
      this.tenantConfig = tenantConfig  
      // 内部外部通知
      this.side = side
      // 系统模版
      if(systemTemplateParam) systemTemplateParam = this.initSysDisplayFieldCheck(systemTemplateParam)
      this.systemTemplate = systemTemplateParam
      // 短信模版 
      if(smsTemplateParam) smsTemplateParam.usageSmsContent = smsTemplateParam.applyContent || ''
      this.smsTemplate = smsTemplateParam
      // 邮箱模版
      if(emailMsgTemplateParam) emailMsgTemplateParam?.attachment?.map(item => {
        const { fileName, ossUrl, fileSizeStr } = item
        item.filename = fileName
        item.url = ossUrl
        item.fileSize = fileSizeStr
      })
      this.emailTemplate = emailMsgTemplateParam
      this.wechatTemplate = wechatMessageTemplateParam
      this.callTemplate = callingTemplateParam
      // 模版以外的数据
      this.bindData.weixin.isSetUp = tenantConfig.isWechatOfficialSetUp
      this.bindData.emailMsg.isSetUp = tenantConfig.isEmailSetUp
      this.form.sendChannelList = sendChannelList
      this.form.notifyConfig = notifyConfig || cloneDeep(init_notifyConfig)
      this.channelList = channelList
      const { channelType } = channelList[0]
      // 默认选中第一个tab 如果短信审核后定位到短信消息
      this.activeName = channelType
      const { paasReceiver = '' } = sendTargetParam
      // 发送对象
      this.updateSendTargetParam(paasReceiver)
    }, 
    getTriggerTemplateField() {
      
      return Message.getTriggerTemplateField(this.bizTypeIds).then(res => {
        
        const { status, data } = res || {}
        
        if(status !== 0) return;
        
        this.triggerTemplateField = (data || []).reduce((result, item)=>{

          result.length === 0 ?
            result.push(item)
            :
            result[0].fieldList = result[0].fieldList.concat(item.fieldList)
          return result
        }, [])
        
      }).catch(err => {
        console.error(err)
      })
      
    },
    
    // 获取该消息的配置数据
    async getTriggerRuleData() {
      try {
        this.loading = true;
        
        const param = {}
        if(this.messageTypeName) param.nodeId = this.messageTypeName
        const { status, data, message } = await Message.getMessageConfig(param);
        
        if( status !== 0){
          this.errors([message])
          return
        }
        this.messageConfig = data
        this.tenantConfig = data?.tenantConfig
        this.getChannelTemplateDetail(data)
        
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },

    // 根据传递的渠道列表，获取相应的调用接口需要的数据
    channelMapPort(channelList) {
      
      const allChannel = {
        sysMsg: {
          port: Message.getSysDetail,
          templateName: 'systemTemplate'
        },
        smsMsg: {
          port: Message.getSmsDetail,
          templateName: 'smsTemplate'
        },
        emailMsg: {
          port: Message.getEmailDetail,
          templateName: 'emailTemplate'
        },
        weixin: {
          port: Message.getWxDetail,
          templateName: 'wechatTemplate'
        },
        call: {
          port: Message.getPhoneDetail,
          templateName: 'callTemplate'
        }
      }

      let messageChannelData = {}
      // 获取当前消息的所有消息渠道的数据
      channelList?.map(channelType => {
        messageChannelData[channelType] = allChannel[channelType]
      })
      return messageChannelData
    },

    getPortParam(){
      return {
        messageTypeName:this.messageTypeName,
        side:this.type === 'inside' ? 0 : 1
      }
    },

    getChannelTemplateDetail(originData) {
      const detailData = originData?.tenantConfig || {}
      if(originData?.notifyConfig){
        this.form.notifyConfig = {
          mode: originData.notifyConfig?.mode || init_notifyConfig.mode,
          timeType: originData.notifyConfig?.timeType || init_notifyConfig.timeType,
          startConfig: originData.notifyConfig?.startConfig?.fieldName ? originData.notifyConfig.startConfig : {...init_notifyConfig.startConfig},
          endConfig: originData.notifyConfig?.endConfig?.fieldName ? originData.notifyConfig.endConfig : {...init_notifyConfig.endConfig},
          strategyConfig: originData.notifyConfig?.strategyConfig?.strategyType ? originData.notifyConfig.strategyConfig : {...init_notifyConfig.strategyConfig},
        }
      }else{
        this.form.notifyConfig = cloneDeep(init_notifyConfig)
      }
      
      // 获取该消息的渠道列表
      let { sendChannelDescriptions = [], outsideSendChannelDescriptions = [] } = detailData?.sendChannels || {}
      
      let channelList = []
      if(this.side == 0) {
        sendChannelDescriptions?.map(item => channelList.push(item.channelType))
      } else {
        outsideSendChannelDescriptions?.map(item => channelList.push(item.channelType))
      }
      
      // 通过该消息的渠道列表获取该消息的渠道列表模版数据的参数
      const channelMapPort = this.channelMapPort(channelList)
      
      const param = this.getPortParam()
      
      let portPromiseArr = []
      
      channelList.map( item => { 
        
        const { templateName } = channelMapPort[item]
        
        if (templateName) {
          
          const data = originData[templateName] || {}
          const result = MsgModel.succ('', data)
          
          portPromiseArr.push(
            Promise.resolve(result)
          )
          
        }
        
      })
      
      Promise.all(portPromiseArr).then((res) => {
        
        if(!res?.length) return
        
        // 存储接口返回的错误
        let errTextArr = [];
        
        for(let index in res){
          const { status, message, data } = res[index] || {}
          
          const channelType = channelList[index]
          
          const { templateName = {} } = channelMapPort[channelType] || {}
          
          if(status !== 0){
            errTextArr.push(message)
            continue;
          }
          
          // 更新指定渠道的消息模版数据
          data && this.updateMsgTemplateData({ channelType, templateName, templateData: data});
          
        }
        // 判断之前是否保存过
        const isEdit = this.nodeConfig.data?.isEditMessage || this.nodeConfig.fieldOptions?.isEditMessage
        if(isEdit) {
          // 保存过
          this.initDefaultData()
        } else {
          // 更新当前表单需要的除模版的数据
          this.setFormData(detailData)
        } 
        errTextArr.length && this.errors(errTextArr);

      })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * @description 更新指定渠道的消息模版数据
     * @param {Object} {channelType:渠道,templateName:该渠道模版名，templateData：该渠道模版内容}
     */
    updateMsgTemplateData(sourceData = {}){
      let { channelType, templateName, templateData = {} } = sourceData

      if(!channelType) return

      if(channelType === 'emailMsg'){
        templateData?.attachment?.map(item => {
          const { fileName, ossUrl, fileSizeStr } = item
          item.filename = fileName
          item.url = ossUrl
          item.fileSize = fileSizeStr
        })
      }

      // if(channelType === 'sysMsg' && this.module === 'paas'){
      //   const defaultSysDisplayFieldCheckMap = templateData?.sysDisplayFieldCheckMap || []
      //   const defaultSysDisplayFieldCheckMapKeys = defaultSysDisplayFieldCheckMap.map(item=> item.key)
      //   // 系统消息过滤应用连接
      //   const sysDisplayFieldCheckMap = this.flowData.msgTemplateSelectFields.filter(item=> !defaultSysDisplayFieldCheckMapKeys.includes(item.fieldValue) && item.fieldValue !== 'smsUrl').map(item=> {
      //     return {
      //       canCancel: true,
      //       check: false,
      //       defaultValue: "xxxxx",
      //       key: item.fieldValue,
      //       value: item.fieldName}
      //   })
      //   if(templateData?.sysDisplayFieldCheckMap && Array.isArray(templateData.sysDisplayFieldCheckMap)) {
      //     templateData.sysDisplayFieldCheckMap = templateData.sysDisplayFieldCheckMap.concat(sysDisplayFieldCheckMap)
      //   }
      // } else 
      if (channelType == 'sysMsg') {
        templateData = this.initSysDisplayFieldCheck(templateData)
      }
      
      templateName && (this[templateName] = templateData);
    },
    // 初始化系统模版字段选中
    initSysDisplayFieldCheck(templateData) {
      // 获取已经勾选的字段
      const defaultTemplateData = cloneDeep(templateData)
      const defaultSysDisplayFieldCheckMap = defaultTemplateData?.sysDisplayFieldCheckMap || []
      const defaultSysDisplayFieldCheckMapKeys = defaultSysDisplayFieldCheckMap.map(item=> item.key)

      const triggerTemplateField = this.triggerTemplateField?.[0] || {}
      const msgTemplateSelectFields = triggerTemplateField?.fieldList || []
      
      const sysDisplayFieldCheckMap = msgTemplateSelectFields.map(item => {
        
        const fieldValue = item?.fieldValue || ''
        const canNotCancel = ['taskNo', 'eventNo', 'serialNumber'].includes(fieldValue)
        const canCancel = !canNotCancel
        
        return {
          canCancel,
          check: defaultSysDisplayFieldCheckMapKeys.includes(item.fieldValue) || canNotCancel,
          defaultValue: "xxxxx",
          key: item.fieldValue,
          value: item.fieldName
        }
        
      })
      
      defaultTemplateData.sysDisplayFieldCheckMap = sysDisplayFieldCheckMap
      return defaultTemplateData
    },
    // 未绑定微信公众号/邮箱提示组件的按钮
    btnEvent(type){

      // 微信公众号设置
      if(type === 'weixin'){
        openAccurateTab({
          type: PageRoutesTypeEnum.PageSettingDoMyself,
          title: '公众号设置',
        })
      }else if(type === 'emailMsg'){
        openAccurateTab({
          type: PageRoutesTypeEnum.PageSettingChannel,
          title: '渠道管理',
          params:'activeTab=email'	
        })
      }

      
    },

    setFormData(data){
      const { 
        taskPlanTime = '', 
        sendChannels = {}, 
        userTypeList = [], 
        sendTargets = {}, 
        isWechatOfficialSetUp = false,
        isEmailSetUp = false
      } = data

      let { avaliableList = [], sendChannelDescriptions = [], outsideSendChannelDescriptions = [] } = sendChannels || {}

      const { paasReceiver = '' } = sendTargets
      

      // paas的暂时过滤相关微信渠道
      // if(this.module === 'paas') sendChannelDescriptions = sendChannelDescriptions.filter(item => item?.channelType !== 'weixin')
      // 发送渠道列表数据
      if(this.side == 0) {
        this.channelList = sendChannelDescriptions || []
      } else {
        this.channelList = outsideSendChannelDescriptions || []
      }
      // 不包含客服云版本时隐藏电话消息
      this.channelList = this.channelList.filter(item => {
        if (item.channelType == 'call') {
          return this._isShowMessagePhoneMessage
        }
        return item
      })
      
      if(this.type === 'customer' && !avaliableList.includes('2')) {
        avaliableList.push('2')
      } else {
        const smsChannelIndex = avaliableList.findIndex(item=> item === '2')
        smsChannelIndex > -1 && avaliableList.splice(1, 1)
      }

      this.$set(this.form, 'sendChannelList', avaliableList || []);

      // 除通用消息外其他消息有通知对象
      this.updateSendTargetParam(paasReceiver) 

      // 发送时间
      this.showTimeField && this.$set(this.form, 'taskPlanTime', taskPlanTime);

      this.sendList = userTypeList || []

      // 是否有配置邮件消息和公众号消息
      this.bindData.weixin.isSetUp = isWechatOfficialSetUp 
      this.bindData.emailMsg.isSetUp = isEmailSetUp

      const { channelType } = this.channelList[0]
      // 默认选中第一个tab 如果短信审核后定位到短信消息
      this.activeName = channelType
    },  

    updateSendTargetParam(paasReceiver){
      if(this.module !== 'universal'){
        let selectedDepartments = []
        let selectedUsers = []
        let selectedRoles = []
        let selectedDynamicList = []
        let nameArr = []
        let parsePaasReceiver = []
        let selectedServiceProviders = []

        try {
          parsePaasReceiver = JSON.parse(paasReceiver) || []
          nameArr = parsePaasReceiver.map(item=> item.name)
        } catch (e) {
          console.warn("Error parsing paasReceiver", e)  
        }
        parsePaasReceiver.map(item => {
          const { id, type, name, logo, staffId } = item
          // typeId 1用户，2部门，4角色，6动态获取
          let newItem = { id, typeId: type, name, logo }

          if(type == 1){
            newItem = {
              userId:id,
              typeId: type,
              staffId,
              displayName: name,
              head:logo
            }
          }

          type == 1 && (selectedUsers.push(newItem));
          type == 2 && (selectedDepartments.push(newItem));
          type == 4 && (selectedRoles.push(newItem));
          type == 5 && (selectedServiceProviders.push(newItem));
          type == 6 && (selectedDynamicList.push(newItem));
        })
        
        this.$set(this.form, 'sendTargetParam', {
          all: parsePaasReceiver.map(item => {
            if(item.typeId == 1) {
              item.id = item.userId
              item.name = item.displayName
            }
            return item
          }),
          nameStr: nameArr,
          selectedDepartments,//选人组件选择的部门
          selectedUsers,//选人组件选择的用户
          selectedRoles,//选人组件选择的角色
          selectedDynamicList, //选人组件选择的动态获取字段列表
          selectedServiceProviders, // 选人组件选择的服务商
          // userTypeList: sendTargets.userTypeList || [],//select组件选择的大类别发送对象
          paasReceiver: paasReceiver,
        });
      }
    },
    
    // 获取通知渠道对应的消息模版组件的异步校验方法和提交的字段
    async getModuleValidate(){
      // 用于存储每个tab需要提交给接口的数据
      let channelTabSubmitParam = {}

      const { sendChannelList } = this.form

      // 将需要校验的消息模版存入channelTabValidate
      let channelTabValidate = []
      // 找到短信渠道
      const channelItem = this.channelList.find(item=>item.channelType === 'smsMsg')
      const { channelType } = channelItem
      const channelDom = this.$refs[channelType] && this.$refs[channelType][0]
      // 编辑状态下的短信消息修改内容点击保存校验提示
      if(channelDom && channelDom.editorStatue && channelDom.isChange()) {
        try {
          const result = await this.$confirm('短信模板文案未提交审核，是否需要提交审核？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          // 这里如果点击确定就调短信提交审核的接口
          if(result === 'confirm') {
            this.submitSmsTemplate(channelDom)
          }
        } catch (error) {
          // 点击取消 不做操作还停留在当前页面
          console.warn(error)
          return {}
        }
      }
      this.channelList.map(item => {
        const { channelType, channel } = item
        const channelDom = this.$refs[channelType] && this.$refs[channelType][0]
        if(channelDom) {
          // // 该渠道是否勾选了
          // const isSelected = sendChannelList.includes(channel)
          // // 校验规则：当勾选了模版，或是没有勾选模版但是有修改模版内容
          // // 提交规则：不管有没有勾选当模版有修改，就要提交

          // // UI现在要改成勾选了渠道才校验必填内容 如果没有勾选渠道不校验
          // if(isSelected && channelDom.isChange()){
          //   // 需要校验的消息模版
          //   channelTabValidate.push(channelDom.validate())
          //   // 需要提交的消息模版内容
          //   channelDom.getParam && (channelTabSubmitParam = { ...channelTabSubmitParam, ...channelDom.getParam() });
          // }

          // 触发器消息不校验是否勾选了渠道以及模版内容是否变化 都需要将各模版参数传给后端 
          // 需要校验的消息模版
          channelTabValidate.push(channelDom.validate())
          // 需要提交的消息模版内容
          channelDom.getParam && (channelTabSubmitParam = { ...channelTabSubmitParam, ...channelDom.getParam() });
        }
      })

      return {
        channelTabValidate,
        channelTabSubmitParam
      }
    },
    // 提交短信审核模版
    submitSmsTemplate(channelDom){
      const { smsTemplateParam = {} } = channelDom.getParam()
      const { applyContent, notice } = smsTemplateParam
      if (!applyContent) return this.$message.warning('模板内容不能为空');
      if ((notice && notice.indexOf('含回访') != -1) && applyContent.indexOf('{smsUrl}') == -1) {
        return this.$message.warning('回访模版必须包含链接地址 {smsUrl} 字段');
      }
      const params = smsTemplateParam;
      params.type = '0';
      this.$http.get('/vipsms/applyTemplate', params).then(res=>{
        if (res.succ) {
          this.$platform.notification({
            type: 'success',
            title: '成功',
            message: '保存成功'
          });
          // 更新短信模版
          const { usageSmsContent } = this.messageConfig.smsTemplate
          smsTemplateParam.usageSmsContent = usageSmsContent
          smsTemplateParam.approveSmsContent = smsTemplateParam.applyContent
          let smsTemplate = {
            channelType: 'smsMsg',
            templateName: 'smsTemplate',
            templateData: smsTemplateParam
          }
          this.updateMsgTemplateData(smsTemplate);
          this.$refs.smsMsg?.[0]?.editorHandle(false)
        } else {
          this.$platform.notification({
            type: 'error',
            title: '失败',
            message: res.message
          });
        }
      });
    },
    submitForm(formName = 'form') {
      this.saveNeedValidTab(formName)
    },

    // 保存时需要校验tab模块
    async saveNeedValidTab(formName = 'form'){
      // 获取选勾选的通知渠道对应的消息模版组件的异步校验方法和提交的字段
      const { channelTabValidate, channelTabSubmitParam } = await this.getModuleValidate()
      // 如果是短信消息编辑了模板保存提示点击取消后return 不进行后续操作
      if(!channelTabValidate) return    
      let validateList = [ this.$refs[formName].validate()]

      // 通用消息，不能编辑消息模版，因此不校验，非通用消息，需要校验
      if(this.module !== 'universal'){
        validateList = [ ...validateList, ...channelTabValidate ]
      }

      // 将需要校验的tab和该弹框的表单的校验组合成promise
      const res = await Promise.all(validateList)
      // 将tab校验的错误结果过滤出来
      let errTextArr = res.filter(val => {
        return typeof val === 'string'
      })
      errTextArr.length && this.errors(errTextArr)
      // 校验成功，调用接口，提交
      if(!errTextArr.length){
        // 调用接口
        const params = this.getParams(channelTabSubmitParam)
        return new Promise(resolve => {
          resolve(params)
        })
      }
    },

    errors(errTextArr = []){
      this.$message({
        customClass:'valid-error-tips',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        message: `${errTextArr?.join('<br/>')}`
      });
    },
    // 获取保存参数
    getParams(channelTabSubmitParam) {
      let param = {
        ...this.form,
        configId: this.configId,
        paasConfigName: this.configId,
        side: this.side,
        ...channelTabSubmitParam
      }

      if(param.notifyConfig){
        if(!param.notifyConfig.startConfig?.fieldName){
          param.notifyConfig.startConfig = {}
        }
        if(!param.notifyConfig.endConfig?.fieldName){
          param.notifyConfig.endConfig = {}
        }
        if(!param.notifyConfig.strategyConfig?.strategyType){
          param.notifyConfig.strategyConfig = {}
        }
      }

      // paas的删除configId
      // if(this.module === 'paas') Reflect.deleteProperty(param, 'configId')

      // this.reportSendTime && (param.reportSendTime = this.reportSendTime);

      const { selectedDepartments = [], selectedUsers = [], selectedRoles = [], selectedDynamicList = [], userTypeList = [], selectedServiceProviders = [] } = param.sendTargetParam
      let sendTargetPartList = []
      let allSendTarget = [...selectedUsers,...selectedRoles,...selectedDepartments, ...selectedDynamicList, ...selectedServiceProviders]

      // 更新paas的发送对象处理（paas不做处理）
      allSendTarget.map(item => {
        const { id, name, displayName, typeId, userId, staffId, logo } = item
        let newItem = {
          id,
          type: typeId,
          name,
        }
        if(typeId == 1){
          newItem = {
            id: userId,
            type: typeId,
            staffId,
            name: displayName,
            head: logo
          }
        }
        sendTargetPartList.push(newItem)
      })

      param.sendTargetParam = {
        userTypeList,
        sendTargetPartList,
        paasReceiver: JSON.stringify(sendTargetPartList)
      }
      // 这里将tenantConfig保存下用于回显，提交数据的时候删除这个参数
      param.tenantConfig = this.tenantConfig
      param.channelList = this.channelList
      if(this.side) {
        param.systemTemplateParam = this.systemTemplate
        param.callingTemplateParam = {
          id: this.callTemplate.templateId,
          ...this.callTemplate
        }
      }
      this.dialogVisible = false
      return param
    },
  }
}
</script>

<style lang="scss" scoped>
.set-message-dialog ::v-deep .el-dialog{
    top: 50%;
    left: 50%; 
    transform: translate(-50%,-50%);
    margin:0 !important;
    .el-dialog__body {
      padding:16px 20px 13px;
      overflow-y: auto;
      max-height: calc(100vh - 100px);
    }
    overflow: visible;
}
.set-message-dialog  {
  .user-target-select{
    width:  300px;
  }
  ::v-deep .user-select{
    /* min-width: 220px; */
    .el-select__tags-text {
      display: inline-block;
      max-width: 90px;
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
    }
    .el-tag__close {
      display: none
    }
  }
}
.el-checkbox{
    margin-right:10px;
}
.channel-item{
    display: inline-block;
    margin-right:34px;
    .el-button--text{
        margin-right:6px;
    }
    .icon-more{
        display:inline-block;
        color:#595959;
        font-size:14px;
        transition: 0.3s all;
    }
    .active{
        .icon-more{
            color:$color-primary-light-6;
            transform:rotate(180deg);
        }
    }
}
.template-content{
    height: 420px;
    background: #F5F5F5;
    border-radius: 4px;
    overflow-y:auto;
}
.send-obj{
    display: flex;
    ::v-deep .el-tag{
      max-width: 110px;
    }
}
.channel-tab{
    min-height:360px;
    margin-bottom: 14px;
    /* ::v-deep .el-tabs__nav-wrap .el-tabs__nav-scroll{
        padding-left:13px;
    } */
   .call-mes-tel{
      ::v-deep  .tips {
        display: none;
      }
    }
}


.apply-range-list  ::v-deep .el-form-item__content{
  .el-select{
    width:182px;
    .el-select__tags span{
      &:first-child{
        max-width:100px;
      }
    }
  }
}
::v-deep {
  .no-auth{
    background:#F5F5F5;
    padding-top:100px;
  }
  .el-form-item--small.el-form-item{
    margin-bottom:14px;
  }
  .send-channel-list{
    .el-form-item__label,.el-checkbox-group,.channel-item{
      height:20px;
      line-height:20px;
    }
  }
  .el-tabs__nav-wrap::after{
    display: none;
  }
  .el-tabs__header{
    margin: 0
  }
}


.paas-send-target__dialog {
  ::v-deep {
    .el-dialog__body{
        padding: 20px;
      }
      .el-dialog__headerbtn{
        top: 4px
    }
  }
}
::v-deep {
  .group-el-form-item .el-form-item__content {
    display: flex;
  }
  .group-el-form-item .el-form-item {
    margin-right: 12px;
    margin-bottom: 0;
  }
  .group-el-form-item-no-margin {
    margin-bottom: 0 !important;
  }
}
</style>
<style lang="scss">
.set-message-dialog {
  .el-dialog{
    .el-dialog__header{
      border-radius: 8px 8px 0 0;
    }
    .el-dialog__headerbtn {
      top: 0;
    }
    .el-dialog__body {
      padding-bottom: 12px;
      .base-editor-container .ql-editor{
        height: 160px;
      }
    }
  }
}
.valid-error-tips{
  padding:7px 16px;
  background: #FDF6EC;
  box-shadow: 0px 9px 28px 8px rgba(0,0,0,0.0500), 0px 6px 16px 0px rgba(0,0,0,0.0800), 0px 3px 6px -4px rgba(0,0,0,0.1200);
  border-radius: 4px;
  border: 1px solid #F9ECDA;
  align-items: flex-start;
  .el-message__icon{
    margin-top:4px;
    font-size:16px;
  }
  .el-message__content{
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #FAAE14;
    line-height: 22px;
  }
}

.trigger-base-select-user-dynamic-user-list {
  .base-select-user-tree-item__count {
    display: none;
  }
}
.message-content{
  .el-form.el-form--label-top .el-form-item__label::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
}

</style>
